/*
 * @Description: 
 * @Author: Liu Kunpeng
 * @Date: 2021-07-05 20:41:06
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-11-16 15:33:27
 */
import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import { getToken, removeToken } from './auth'
import router from '@/router'

// create an axios instance
const service = axios.create({
  withCredentials: true, // send cookies when cross-domain requests
  // timeout: 20000 // request timeout

})

if (process.env.NODE_ENV === 'development') {
  service.defaults.baseURL = "http://localhost:8880"
} else if (process.env.NODE_ENV === 'production') {
  service.defaults.baseURL = "http://124.70.206.18:8880"
}

// request interceptor
service.interceptors.request.use(
  config => {
    //携带token
    let token = getToken();
    //若token存在，加上token
    token && (config.headers.Authorization = "Bearer" + " " + token);
    return config
  },
  error => {
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    
    const res = response.data
    if(res.code == undefined){
      return res
    }
    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== 20000 ) {
      Message({
        message: res.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })

      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.code === 30001 || res.code === 30002 || res.code === 30003 || res.code === 30004) {
        // to re-login
        MessageBox.confirm('登陆已过期，请重新登录', '登陆已过期，请重新登录。', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          removeToken()
          router.push('/login')
        })
      }
      if(res.code === 30005){
        Message.info('权限不足')
        router.push('/404')
      }
      return Promise.reject(new Error(res.message || '未知错误'))
    }else {
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message || '未知错误',
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
